package com.pan.alg.niuke.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeUtil {

    public static TreeNode generateTree(int[] arr){

        Queue<TreeNode> treeNodes = new LinkedList<>();
        TreeNode head = new TreeNode(arr[0]);
        treeNodes.add(head);
        int index = 0;
        while(!treeNodes.isEmpty()){
            TreeNode poll = treeNodes.poll();
            index++;
            if(index>=arr.length){
                break;
            }
            TreeNode left = new TreeNode(arr[index]);
            poll.left=left;
            treeNodes.offer(left);

            index++;
            if(index>=arr.length){
                break;
            }
            TreeNode right = new TreeNode(arr[index]);
            poll.right=right;
            treeNodes.offer(right);
        }
        return head;
    }

    public static void printTree(TreeNode treeNode){
        Queue<TreeNode> level = new LinkedList<>();
        level.add(treeNode);

        while (!level.isEmpty()){
            int size = level.size();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                TreeNode poll = level.poll();
                sb.append(poll.val).append("-");
                if(poll.left!=null){
                    level.add(poll.left);
                }
                if(poll.right!=null){
                    level.add(poll.right);
                }
            }
            System.out.println(sb);
        }
    }

    public static void main(String[] args) {
        int[] tree = new int[]{1,2,3,4,5,6};
        TreeNode head = generateTree(tree);
        printTree(head);
        System.out.println(head);

    }
}
